package com.demo.base.resolver;
import javax.servlet.http.HttpServletRequest;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.demo.base.anno.Params;
import com.demo.base.exception.ParamException;

/**
 * Created by 12614 on 2018/5/11.
 */
public class ParamArgValidorResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //如果函数包含我们的自定义注解，那就走resolveArgument()函数
        return methodParameter.hasParameterAnnotation(Params.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        Params params = methodParameter.getParameterAnnotation(Params.class);
        String paramName = params.name();
        if ("".equals(paramName)) {
            paramName = methodParameter.getParameterName();
        }
        //简单的案例：如果客户端未传值，就设置默认值
        Object res = nativeWebRequest.getNativeRequest(HttpServletRequest.class).getParameter(paramName);
        String argValue = res == null ? params.defaultValue() : (String) res;
        if(argValue!=null) {
        	if(argValue.length()>params.maxLength()) {
        		throw new ParamException(paramName+"参数太长！");
        	}
        }else {
        	if(params.notEmpty()) {
        		throw new ParamException(paramName+"参数不能为空！");
        	}
        }
        return argValue;
    }
}